package netty.server;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;

@Slf4j
public class UdtBytesServerHandler extends SimpleChannelInboundHandler<Object> {
    
    public UdtBytesServerHandler() {
        log.info(">>> init {}", this.toString());
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            // discard
            // Do something with msg
            log.info("receive data: {}, {}", msg, ctx.channel().remoteAddress());
            ByteBuf buf = (ByteBuf) msg;
            ctx.write(msg);
            log.info("receive data: {}", buf.toString(Charset.defaultCharset()));
        } finally {
//            ReferenceCountUtil.release(msg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // Close the connection when an exception is raised.
        cause.printStackTrace();
        ctx.close();
    }
}